<template>
  <div v-loading="loading" class="container">
    <el-form ref="form" label-position="left" size="mini">

      <el-form-item label="数据库:">
        <el-select
          v-model="dbSelectCondition"
          style="min-width: 260px"
          clearable
          filterable
          placeholder="请选择数据库"
        >
          <el-option
            v-for="item in dbSelecteds"
            :key="item.id"
            :label="item.tags + '|' + item.host"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="SQL语句:">
        <el-input
          v-model="inputSql"
          type="textarea"
          :rows="6"
          placeholder="请输入SQL"
        />
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" @click="onClickDiagnose">开始优化
        </el-button>
      </el-form-item>

    </el-form>
    <el-card shadow="always">
      <div style="padding: 0 30px;">
        <el-tabs v-model="analyseActionName" @tab-click="analyseActionHandleClick">
          <el-tab-pane label="根因分析" name="baseinfo">
            <div ref="causeSuggestContainer" style="overflow: auto; height: 500px">
              <div
                v-for="(item, index) in sqlExplains"
                :key="index"
                class="sqlContainer"
                style="padding: 10px; margin-bottom: 10px; color:
                            #333333"
              >
                <span style="color: #666666">根因：</span>{{ item.nodeType }}<br><span style="color: #666666">执行代价：</span> {{ item.cost }}
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="索引建议" name="index">
            <div ref="indexSuggestContainer" style="overflow: auto; height: 500px">
              <div v-for="(item, index) in sqlIndexSelections" :key="index" class="indexSuggestSetp">
                <div class="indexSuggestSetpTitle">
                  {{ index+1 }}. 创建索引
                </div>
                <div class="sqlContainer">
                  <div class="copyContainer">
                    <div class="copy-to-clipboard" @click="handleCopy(item.query)">
                      <el-tooltip class="item" effect="dark" content="复制SQL到剪贴板" placement="top-end">
                        <i class="el-icon-document-copy" />
                      </el-tooltip>
                    </div>
                  </div>
                  <highlightjs :code="sqlFormatter(item.query)" />
                </div>
              </div>
            </div>

          </el-tab-pane>
          <el-tab-pane label="执行计划" name="plan">
            <div ref="planSuggestContainer" style="overflow: auto; height: 500px; width: 100%" >
              <VChart class="planTreeChart" :option="planTreeChartOption" autoresize />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

  </div>
</template>

<script>

import { format } from 'sql-formatter'
import { pgsqlServersSimpleInfo, sqlExplain, sqlIndexSelection, sqlPlans } from '../../api/api'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { TreeChart } from 'echarts/charts'

import {
  TooltipComponent
} from 'echarts/components'
import { default as VChart, THEME_KEY } from 'vue-echarts'

use([
  CanvasRenderer,
  TreeChart,
  TooltipComponent
])

export default {
  components: {
    VChart
  },
  provide: {
    [THEME_KEY]: 'light'
  },
  filters: {
    sqlFilter: function(value) {
      if (!value) {
        return ''
      }
      return value.length > 30 ? (value.slice(0, 30) + '...') : value
    }
  },
  data() {
    return {
      loading: false,
      sqlFormatter: format,
      dbSelecteds: [],
      dbSelectCondition: 1,
      inputSql: 'SELECT * FROM nation, customer, orders WHERE n_regionkey BETWEEN 0.16 AND 0.33 AND c_acctbal > -473.72 AND o_custkey > 104750.04 AND n_nationkey = c_nationkey AND c_custkey = o_custkey;',
      sqlExplains: [],
      sqlIndexSelections: [],
      analyseActionName: 'baseinfo',
      planTreeChartOption: {
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove',
          formatter: '{b0}'
        },
        series: [
          {
            type: 'tree',
            id: 0,
            name: 'tree',
            data: [],
            symbolSize: 7,
            edgeShape: 'polyline',
            edgeForkPosition: '63%',
            initialTreeDepth: -1,
            lineStyle: {
              width: 2
            },
            label: {
              backgroundColor: '#fff',
              position: 'left',
              verticalAlign: 'middle',
              align: 'right'
            },
            leaves: {
              label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            },
            emphasis: {
              focus: 'descendant'
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      }
    }
  },
  mounted() {
    this.getPgsqlServersSimpleInfo()
  },
  destroyed() {
  },
  methods: {
    getPgsqlServersSimpleInfo() {
      pgsqlServersSimpleInfo({}).then((res) => {
        this.dbSelecteds = res.data
        this.dbSelectCondition = this.dbSelecteds[0].id
      }).catch(() => {
      })
    },
    getSqlExplain() {
      sqlExplain({ sql: this.inputSql }).then((res) => {
        this.sqlExplains = res.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getSqlIndexSelection() {
      sqlIndexSelection({ workload: JSON.stringify([this.inputSql]) }).then((res) => {
        this.sqlIndexSelections = res.result_list
      }).catch(() => {
      })
    },
    getPlans() {
      const that = this
      sqlPlans({ workload: JSON.stringify([this.inputSql]) }).then((res) => {
        that.planTreeChartOption.series[0].data = [res.data]
      }).catch(() => {
      })
    },
    onClickDiagnose() {
      this.loading = true
      this.getSqlExplain()
      this.getSqlIndexSelection()
      this.getPlans()
    },
    handleCopy(value) {
      const that = this
      this.$copyText(value).then(function(e) {
        that.$message.success(' 已复制到剪贴板！')
        console.log(e)
      }, function(e) {
        that.$message.error('复制失败，请使用Ctrl+C复制')
        console.log(e)
      })
    },
    analyseActionHandleClick(tab) {
      switch (tab.name) {
        case 'cause':
          this.$refs['causeSuggestContainer'].style.height = Math.max(window.innerHeight - 450, 100) + 'px'
          break
        case 'index':
          this.$refs['indexSuggestContainer'].style.height = Math.max(window.innerHeight - 450, 100) + 'px'
          break
        case 'rewrite':
          this.$refs['planSuggestContainer'].style.height = Math.max(window.innerHeight - 450, 100) + 'px'
          break
        default:
          break
      }
    }
  }
}

</script>

<style lang="scss" scoped>

  @import "../../styles/vue-hljs-theme.css";
  @import "../../styles/table.css";

  .container {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .top-card-title {
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
    line-height: 22px;
  }

  .top-card-detail {
    color: rgba(0, 0, 0, 0.85);
    font-weight: bolder;
    white-space: nowrap;
    word-break: break-all;
    font-size: 30px;
    line-height: 60px;
  }

  .card-header-title {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    white-space: nowrap;
    word-break: break-all;
    font-size: 18px;
  }

  .el-divider--horizontal {
    margin: 20px 0;
  }

  .el-col-5 {
    width: 20%;
  }

  .table_container {
    overflow: auto;
  }

  .table_btns_container {
    display: flex;
    flex-direction: row;
    align-content: space-around;
    height: 30px;
    line-height: 30px;
    margin: 10px auto;
    width: 100%;
  }

  .table_btns_item_container {
    flex: 0 0 33.333%;
    display: flex;
    justify-content: center;
  }

  .healthChart {
    width: 100%;
    height: 260px;
  }

  .sqlQueryChart {
    width: 100%;
    height: 300px;
  }

  .sqlSlowQueryChart {
    width: 100%;
    height: 300px;
  }

  .report-list-container {
    height: 190px;
    width: 100%;
    overflow: auto;
  }

  .report-list-item {
    width: 100%;
    height: 40px;
    line-height: 40px;
    display: flex;
    color: rgba(0, 0, 0, 0.65);
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
  }

  .dialogSectionHeaderTitle {
    font-size: 16px;
    color: #333333;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .sqlContainer {
    width: 80%;
    background: #f5f5f5;
    border-radius: 4px;
    white-space: pre;
    padding: 0 10px;
    color: #000000;
    font-size: 1em;
    position: relative;
    text-align: left;
  }

  .copyContainer {
    position: absolute;
    right: 6px;
    top: 6px;
  }

  .el-icon-document-copy:hover {
    color: #409EFF;
  }

  .el-icon-document-copy:active {
    color: #000000;
  }

  .planTreeChart {
    width: 100%;
    height: 500px;
  }

  .el-drawer:focus {
    outline: none;
  }

  .indexSuggestSetp {
    margin-top: 10px;
  }

  .indexSuggestSetpTitle {
    color: #666666;
    font-size: 10px;
    line-height: 30px;
  }

  div.echarts {
    width: 100%;
    height: 100%;
  }

</style>

